package examples.ejb.ejb20.basic.inventory;

import java.rmi.RemoteException;
import java.util.Hashtable;
import javax.ejb.CreateException;
import javax.ejb.RemoveException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.rmi.PortableRemoteObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * This class illustrates calling a stateless Session Bean and performing
 * the following exercises:
 * <ul>
 * <li> Create a Trader
 * <li> Buy some shares using the Trader
 * <li> Sell some shares using the Trader
 * <li> Remove the Trader
 * </ul>
 *
 * @author Copyright (c) 1998-2008 by BEA Systems, Inc. All Rights Reserved.
 */
public class Client
{
  private static final String JNDI_NAME = "ejb20-inventory-InventoryHome";
  private String url;
  private InventoryHome home;
  Hashtable<String,String[]> inventoryTable;

  public Client(String url) throws NamingException {
    this.url = url;
    home = lookupHome();
  }
  
	private void printAll(Inventory inventory){
		try{
			inventoryTable = inventory.getInventoryTable();
			for (String theKey : inventoryTable.keySet()){
				String[] theRec = inventoryTable.get(theKey);
				System.out.println(theRec[0]+" "+theRec[1]+" "+theRec[2]);
			}
		} catch (Exception e) {
				log("There was an exception printing all elemements");
		}
	}
	
	private void printKey(Inventory inventory, String input){
		try{
			inventoryTable = inventory.getInventoryTable();
			String[] theRec = inventoryTable.get(input);
			if (theRec!=null){
				System.out.println(theRec[0]+" "+theRec[1]+" "+theRec[2]);
			}
		} catch (Exception e) {
			log("There was an exception printing key");
		}
	}  
    
  
  
  /**
   * Runs this example from the command line. Example:
   * <p>
   * <tt>java examples.ejb.ejb20.basic.inventory.Client "t3://localhost:7001"</tt>
   * <p>
   * The parameters are optional, but if any are supplied,
   * they are interpreted in this order:
   * <p>
   * @param args               URL such as "t3://localhost:7001" of Server
   */
  public static void main(String[] args) throws Exception {
    log("\nBeginning inventory.Client...\n");
    String url       = "t3://localhost:7001";
    Client client = null;

    // Parse the argument list
     if (args.length > 1) {
      log("Usage: java examples.ejb.ejb20.basic.inventory.Client t3://hostname:port");
      return;
    } else if (args.length == 1) {
      url = args[0];
    }

    try {
      client = new Client(url);
      client.example();
    } catch (NamingException ne) {
      log("Unable to look up the beans home: " + ne.getMessage());
      throw ne;
    } catch (Exception e) {
      log("There was an exception while creating and using Inventory.");
      log("This indicates that there was a problem communicating with the server: "+e);
      throw e;
    }

    log("\nEnd inventory.Client...\n");
  }

  /**
   * Runs this example.
   */
  public void example()
    throws CreateException, RemoteException, RemoveException
  {
    // create an Inventory
    log("Performing inventory");
    Inventory inventory = (Inventory) narrow(home.create(), Inventory.class);
    
    System.out.println("Existing Inventory:");
    printAll(inventory);
  
	String line=null;
	Pattern extPattern=Pattern.compile("(.*)\\*(.*)\\*(.*)\\*");
	System.out.println("Loading from input_inventory:");
	BufferedReader reader;
	try {
		reader = new BufferedReader(new InputStreamReader(new BufferedInputStream(
				new FileInputStream(inventory.getINVENTORYINPUTTEXT()))));
		while ((line=reader.readLine())!=null){
			Matcher matcher = extPattern.matcher(line.trim());
			while (matcher.find()){
				System.out.println("...."+matcher.group(1)+"  "+matcher.group(2)+"  "+matcher.group(3));
				inventory.add(matcher.group(1),  matcher.group(2),  Integer.parseInt(matcher.group(3)));
			}
		}
	} catch (FileNotFoundException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	}
	
	System.out.println("Inventory after input:");
	printAll(inventory);
	
	System.out.println("testing adds and removes:");
	System.out.println("add(11111,Title 1,5)");
	inventory.add("11111","Title 1",5);
	printKey(inventory,"11111"+"Title 1");
	System.out.println("add(11111,Title 1,2)");
	inventory.add("11111","Title 1",2);
	printKey(inventory,"11111"+"Title 1");
	System.out.println("remove(11111,Title 1,2)");
	inventory.remove("11111","Title 1",2);
	printKey(inventory,"11111"+"Title 1");
	System.out.println("remove(11111,Title 1,35)");
	inventory.remove("11111","Title 1",35);
	
	System.out.println("Updated Inventory:");
	printAll(inventory);
	
    // remove the Trader
    log("Removing Inventory");
    inventory.remove();
  }

  /**
   * RMI/IIOP clients should use this narrow function
   */
  private Object narrow(Object ref, Class c) {
    return PortableRemoteObject.narrow(ref, c);
  }
  
  
  /**
   * Lookup the EJBs home in the JNDI tree
   */
  private InventoryHome lookupHome() throws NamingException {
    // Lookup the beans home using JNDI
    Context ctx = getInitialContext();
    try {
      Object home = ctx.lookup(JNDI_NAME);
      return (InventoryHome) narrow(home, InventoryHome.class);
    } catch (NamingException ne) {
      log("The client was unable to lookup the EJBHome.  Please make sure ");
      log("that you have deployed the ejb with the JNDI name "+
        JNDI_NAME+" on the WebLogic server at "+url);
      throw ne;
    }
  }

  /**
   * Using a Properties object will work on JDK 1.1.x and Java2
   * clients
   */
  private Context getInitialContext() throws NamingException {
    
    try {
      // Get an InitialContext
      Hashtable<String,String> h = new Hashtable<String,String>();
      h.put(Context.INITIAL_CONTEXT_FACTORY,
        "weblogic.jndi.WLInitialContextFactory");
      h.put(Context.PROVIDER_URL, url);
      return new InitialContext(h);
    } catch (NamingException ne) {
      log("We were unable to get a connection to the WebLogic server at "+url);
      log("Please make sure that the server is running.");
      throw ne;
    }
  }

  private static void log(String s) { System.out.println(s); }
  
}
